package com.qinge.blog.utils.mybatis.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author QDW
 * @date 2022/5/9 11:12
 * @description MetaObjectHandler，自动填充的第二种方法 使用MyBatis Plus的处理器  第一种方式是自定义的注解CreateTime等方式
 **/
@Component
@Configuration
public class DefaultMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        // 布尔值填充字段
        // 目前只有用户的字段
        String[] booleanArr=new String[]{"enabled","accountNonExpired","accountNonLocked","credentialsNonExpired"};

        // 自动填充bool，防止直接插入报错
        // Arrays.stream(booleanArr).forEach(each->   metaObject.setValue(each, true) );
        forceFill(metaObject,booleanArr,true);

        // 时间填充
        String[] dateArr=new String[]{"createTime","updateTime"};

        Arrays.stream(dateArr).forEach(each-> this.fillStrategy(metaObject, each,new Date()));
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 时间填充
        String[] dateArr=new String[]{"updateTime"};

        Arrays.stream(dateArr).forEach(each-> this.fillStrategy(metaObject, each, new Date()));
    }

    /**
     * @author QDW
     * @date 2022/5/9 21:13
     * @description 强制填充
     * @param metaObject
     * @param fieldNames
     * @param fieldVal
     * @return com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
     **/
    private MetaObjectHandler forceFill(MetaObject metaObject,String[] fieldNames, Object fieldVal) {
        TableInfo tableInfo=findTableInfo(metaObject);

        List<String> talbeFieldNames=tableInfo.getFieldList().stream().map(each -> each.getProperty()).collect(Collectors.toList());

        for (String fieldName:fieldNames) {
            if(talbeFieldNames.contains(fieldName)){
                setFieldValByName(fieldName,fieldVal,metaObject);
            }
        }

        return this;
    }
}
